/*
 * UDPClient.cpp
 *
 *  Created on: Dec 29, 2014
 *      Author: toti
 */

#include <Connectivity/UDPClient.hpp>

UDPClient::UDPClient(std::string &address, std::string &port) {

	this->address = address;
	this->port = port;
	this->sock = -1;

	this->psinfo = 0;
	memset(&sainfo, 0, sizeof(struct addrinfo));


}

void UDPClient::initMulticast() {

	sock = socket(PF_INET6, SOCK_DGRAM, 0);

	memset(&sainfo, 0, sizeof(struct addrinfo));

	sainfo.ai_flags = 0;
	sainfo.ai_family = PF_INET6;
	sainfo.ai_socktype = SOCK_DGRAM;
	sainfo.ai_protocol = IPPROTO_UDP;
	getaddrinfo(address.c_str(), port.c_str(), &sainfo, &psinfo);

	int multicastTTL = 1;
	setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char*) &multicastTTL, sizeof(multicastTTL));

	in_addr_t iface = INADDR_ANY;

	setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char*) &iface, sizeof(iface));

}

void UDPClient::initUnicast() {

	sock = socket(PF_INET6, SOCK_DGRAM, 0);

	memset(&sainfo, 0, sizeof(struct addrinfo));

	sainfo.ai_flags = 0;
	sainfo.ai_family = PF_INET6;
	sainfo.ai_socktype = SOCK_DGRAM;
	sainfo.ai_protocol = IPPROTO_UDP;
	getaddrinfo(address.c_str(), port.c_str(), &sainfo, &psinfo);

	in_addr_t iface = INADDR_ANY;

	setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char*) &iface, sizeof(iface));

}

int UDPClient::sendDatagram(size_t len, void *data) {

	unsigned int addressLen = sizeof(struct sockaddr_in6);

	return sendto(sock, data, len, 0, (struct sockaddr *) psinfo->ai_addr, addressLen);

}
